<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace app\index\model;

use think\facade\Db;
use app\common\model\Common;
use app\index\model\UserLog as userLogModel;

class User extends Common
{
    const STATUS_NORMAL = 1;        //用户状态 正常

    /**
     * 用户账户密码登陆
     * @param $data
     * @param int $loginType
     * @param int $platform
     * @return array|mixed
     */
    public function toLogin($data, $loginType = 1, $platform = 1)
    {
        $result = array(
            'status' => false,
            'data'   => '',
            'msg'    => ''
        );
        if (!isset($data['username']) || !isset($data['password'])) {
            $result['msg'] = '邮箱和密码不为空.';
            return $result;
        }
        if(empty($data['username']) || empty($data['password'])){
            $result['msg'] = '邮箱和密码不为空.';
            return $result;
        }
        $vercode   = $data['vercode'] ?? '';
        $agreement = $data['agreement'] ?? '';
        $username  = $data['username'];

        $userInfo = Db::name('user')->where(['username' => $username])->find();
        if (!$userInfo) {
            $user_check_list = Db::name('user_check')->where(array('username' => $username))->find();
            if($user_check_list){
                $result['msg'] = 'The account is under review';
            }else{
                $result['msg'] = 'The account was not found';
            }
            return $result;
        }
        //判断用户名和密码是否正确登陆
        $userInfo = Db::name('user')->where([
            'username' => $data['username'],
            'password' => $this->enPassword($data['password'], $userInfo['ctime'])
        ])->find();

        if ($userInfo) {
            $current_ip     = ip();
            $current_time   = getUtcTime();
            $user_id        = $userInfo['id'];

            if ($userInfo['status'] == self::STATUS_NORMAL) {
                if(!empty($vercode)){
                    $session_check_user         = session("user_{$username}_check_login");
                    $session_check_user_time    = session("user_{$username}_check_login_time");

                    if(($current_time - $session_check_user_time) >= 5*60){
                        $result['status']   = '100020'; //验证码过期
                        $result['msg']      = 'Captcha has expired.';
                        return $result;
                    }
                    if($vercode != $session_check_user){
                        $result['status']   = '100030'; //验证码错误
                        $result['msg']      = 'Captcha error.';
                        return $result;
                    }
                    session("user_{$username}_check_login" , null);
                    session("user_{$username}_check_login_time" , null);
                }else{
                    $no_check_user = getSetting('no_check_username');
                    $no_check_list = [];
                    if(!empty($no_check_user)){
                        $no_check_list = explode(',',$no_check_user);
                    }
                    $user_id_array = [];
                    if(!empty($no_check_list)){
                        foreach($no_check_list as $kk=>$vv){
                            $user_id_array[] = Db::name('user')->where(['username'=>$vv])->value('id');
                        }
                    }
                    if(!in_array($user_id , $user_id_array)){
                        //判断此ip是否登录过
                        $user_ip_list   = Db::name('user_ip')->where(['user_id'=>$user_id])->select()->toArray();
                        $ip_array = [];
                        if(!empty($user_ip_list)){
                            foreach ($user_ip_list as $k=>$v){
                                $ip_array[] = $v['ip'];
                            }
                        }

//                        if(!in_array($current_ip , $ip_array)){
//                            $result['status']   = '100010'; //此ip从未登录过
//                            $result['msg']      = 'This mailbox has never been logged in.';
//                            return $result;
//                        }
                    }
                }

                $userTokenModel = new UserToken();
                $user_token     = $userTokenModel->setToken(['user_id' => $userInfo['id']]);

                session('user', $userInfo);
                session('user_token', $user_token);

                $result['status'] = true;
                //记录登录日志
                userLogModel::setLog($user_id , userLogModel::USER_LOGIN);
                //记录用户ip
                if(!empty($agreement)){
                    Db::name('user_ip')->save([
                        'user_id'   => $user_id,
                        'ip'        => $current_ip,
                        'ctime'     => $current_time
                    ]);
                }else{
                    $user_ip_list = Db::name('user_ip')->where(['user_id' => $user_id,'ip' =>$current_ip])->find();
                    if($user_ip_list){
                        Db::name('user_ip')->where(['user_id' => $user_id,'ip' =>$current_ip])
                            ->update(['ctime' => $current_time]);
                    }
                }
                //hook('loginAfter',$userInfo);//登录后事件
            } else {
                $result['msg'] = 'This account has been disabled';
                return $result;
            }
        } else {
            $result['msg'] = 'Password error, please try again';
        }
        return $result;
    }

    /**
     * 密码加密方法
     * @author 救火队队长
     */
    private function enPassword($password, $ctime)
    {
        return md5(md5($password) . $ctime);
    }

    public function pwdChange($username,$password)
    {
        $user_list  = Db::name('user')->where(['username' => $username])->find();
        $ctime      = $user_list['ctime'];
        $user_id    = $user_list['id'];
        $new_pwd    = md5(md5($password) . $ctime);
        $re = Db::name('user')->where(['id'=>$user_id])->update([
            'password'  => $new_pwd,
            'utime'     => getUtcTime()
        ]);
        userLogModel::setLog($user_id , 'change pwd' ,['username' => $username , 'password' => $password]);
        return $re;
    }
}
